//-------------------------------------------------------------------------------
// <copyright file="Repository.cs" company="bbv Software Services AG">
//   Copyright (c) 2009 bbv Software Services AG
//
//   Licensed under the Apache License, Version 2.0 (the "License");
//   you may not use this file except in compliance with the License.
//   You may obtain a copy of the License at
//
//       http://www.apache.org/licenses/LICENSE-2.0
//
//   Unless required by applicable law or agreed to in writing, software
//   distributed under the License is distributed on an "AS IS" BASIS,
//   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//   See the License for the specific language governing permissions and
//   limitations under the License.
// </copyright>
//------------------------------------------------------------------------------
using System;
using System.Transactions;
using bbv.DomainDrivenDesign.Interfaces;

namespace O1.Social.Newsgator.Repository.LinqToSql
{
    /// <summary>
    ///   Implements a base class of a repository based on the DDD pattern by Eric Evans.
    /// </summary>
    /// <typeparam name="TEntity">
    ///   The type of the repository.
    /// </typeparam>
    public abstract class Repository<TEntity, TDataTransferObject, TId> : ReadOnlyRepository<TEntity, TDataTransferObject, TId>,
                                                                          IRepository<TDataTransferObject, TId>
        where TEntity : class, new()
        where TDataTransferObject : class, IDataTransferObject<TId>
        where TId : IComparable<TId>
    {
        protected new virtual IConverter<TDataTransferObject, TEntity> Converter
        {
            get;
            set;
        }
        protected Func<IWorkspace> GetWorkspaceForSave { get; private set; }

        #region Constructor
        
        protected Repository(IConverter<TDataTransferObject, TEntity> converter) : this(new LinqToSqlWorkspaceProvider(), converter) { }

        protected Repository(IWorkspaceProvider workspaceCreator, IConverter<TDataTransferObject, TEntity> converter)
            : base(workspaceCreator, converter)
        {
            GetWorkspaceForSave = () =>
            {
                var ws = workspaceCreator.Workspace;
                DefaultIncludesForUpdate(ws);
                return ws;
            };

            Converter = converter;
        }
        #endregion

        #region Protected methods
        protected virtual void DefaultIncludesForUpdate(IWorkspace workspace) { }
        protected virtual void AuditingOnSubEntityCreate(TEntity entity) { }
        protected virtual void AuditingOnSubEntityUpdate(TEntity entity) { }
        #endregion

        #region IRepository<TEntity,TDataTransferObject,TId> Members
        /// <summary>
        ///   Adds the specified item to the
        ///   <see cref="IWorkspace" />
        ///   .
        /// </summary>
        /// <param name="item">The item to add.</param>
        public virtual void Create(TDataTransferObject item)
        {
            using (var context = GetWorkspaceForSave())
            {
                var entity = new TEntity();

                Converter.ConvertBack(item, entity);

                var auditing = entity as IAuditing;
                if (auditing != null)
                {
                    auditing.CreationDate = DateTime.Now;
                    AuditingOnSubEntityCreate(entity);
                }
                
                UpdateAuditing(item as IAuditing, entity as IAuditing);
                
                Converter.Update(item, context.Create(entity));                
            }
        }
        /// <summary>
        ///   Deletes the specified item to the
        ///   <see cref="IWorkspace" />
        ///   .
        /// </summary>
        /// <param name="item">The item to delete.</param>
        public virtual void Delete(TDataTransferObject item)
        {
            using (var context = GetWorkspace())
            {
                var transactionOptions = new TransactionOptions
                                             {
                                                 IsolationLevel = IsolationLevel.ReadCommitted
                                             };
                using (var transactionScope = new TransactionScope(TransactionScopeOption.Required, transactionOptions))
                {
                    var entity = context.GetById<TEntity, TId>(item.Id);
                    context.Delete(entity);
                    transactionScope.Complete();
                }
            }
        }
        /// <summary>
        ///   Updates the specified item to the
        ///   <see cref="IWorkspace" />
        ///   .
        /// </summary>
        /// <param name="item">The item to update.</param>
        public virtual void Update(TDataTransferObject item)
        {
            using (var context = GetWorkspaceForSave())
            {
                var transactionOptions = new TransactionOptions
                                             {
                                                 IsolationLevel = IsolationLevel.ReadCommitted
                                             };
                using (var transactionScope = new TransactionScope(TransactionScopeOption.Required, transactionOptions))
                {
                    var entity = context.GetById<TEntity, TId>(item.Id);

                    Converter.ConvertBack(item, entity);

                    var auditing = entity as IAuditing;
                    if (auditing != null)
                    {
                        auditing.LastModifiedDate = DateTime.Now;
                        AuditingOnSubEntityUpdate(entity);
                    }

                    context.Update(entity);
                    context.SubmitChanges();

                    UpdateAuditing(item as IAuditing, entity as IAuditing);

                    transactionScope.Complete();
                }
            }
        }

        private void UpdateAuditing<TDataTransferObject, TEntity>(TDataTransferObject item, TEntity entity)
            where TDataTransferObject : class, IAuditing
            where TEntity : IAuditing
        {
            var auditingConverter = Converter as IAuditingConverter;
            if (auditingConverter != null && item != null)
            {
                auditingConverter.ConvertAudit(item, entity);
            }
        }

        /// <summary>
        /// Creates or Updates an item depending on if it exists in the database.
        /// </summary>
        /// <param name="item"></param>
        public void CreateOrUpdate(TDataTransferObject item)
        {
            using (var context = GetWorkspaceForSave())
            {
                var entity = context.GetById<TEntity, TId>(item.Id);
                if (entity == null)
                {
                    Create(item);
                }
                else
                {
                    Update(item);
                }
            }
        }
        #endregion
    }
}